package com.teamone.etl.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author 1752140@qq.com
 * 2021/1/13
 */
public class ScriptRunnerExecSql{

    /**
     * 数据库地址
     */
    private static final String DB_HOST ="rm-uf6c53o73klwrsdteuo.mysql.rds.aliyuncs.com";
    /**
     * 数据库名称
     */
    private static final String DB_NAME ="etl_dataruleengine";
    /**
     * 登录名称
     */
    private static final String USER_NAME = "hongwei";
    /**
     * 登录密码
     */
    private static final String USER_PASSWORD = "HongWei1804";
    /**
     * 端口号
     */
    private static final String DB_PORT ="3306";


    /**
     * 根据传入文件名，执行对应.sql脚本
     * @param functionName
     * @return
     */
    public static boolean execute(String functionName) {
        try {
            //获取连接
            Connection conn =getMySqlConnection();
            ScriptRunner runner = new ScriptRunner(conn);
            //设置字符集,不然中文乱码插入错误
            Resources.setCharset(StandardCharsets.UTF_8);
            //定义命令间分隔符
            runner.setDelimiter(";");
            runner.setFullLineDelimiter(false);
            //设置是否输出日志
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            //true，遇见错误会停止执行，打印并抛出异常，捕捉异常，并进行回滚，保证在一个事务内执行；
            runner.setStopOnError(true);
            // 从class目录下直接读取
            runner.runScript(Resources.getResourceAsReader("\\com\\teamone\\etl\\dataruleengine\\database\\"+functionName+".sql"));
            runner.closeConnection();
            conn.close();
            System.out.println("sql执行成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("sql执行异常");
            return false;
        }
    }

    /**
     * @功能描述：   获取数据库连接
     *
     * @return
     * @throws Exception
     */
    public static Connection getMySqlConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://"+ DB_HOST +":"+ DB_PORT +"/"+ DB_NAME +"?useUnicode=true&characterEncoding=utf-8&port="+ DB_PORT +"&autoReconnect=true";
        return DriverManager.getConnection(url, USER_NAME, USER_PASSWORD);
    }

}
